package com.example.springboottestgit.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.example.springboottestgit.bean.TenderContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * @description:
 * @author: ZZZ
 */
@Service
public class ElasticSearchClientServer {
    @Autowired
    private ElasticsearchClient client;

    //创建索引
    public void createIndex(String indexName) throws IOException {
        client.indices().create(c -> c.index(indexName));
    }

    public boolean existsTest(String indexName) throws IOException {
        BooleanResponse booleanResponse = client.indices().exists(e -> e.index(indexName));
        return booleanResponse.value();
    }

    public boolean deleteTest(String indexName) throws IOException {
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index(indexName));
        return deleteIndexResponse.acknowledged();
    }

    public void createIndexContent(String indexName, String filePath, String splits) throws Exception {
        BooleanResponse exists = client.indices().exists(e -> e.index(indexName));
        if (!exists.value()) {
            client.indices().create(c -> c.index(indexName));
            //文本内容
            // 根据 $$$$$ 分割入库
            String textContent = textContent(filePath).replace("#####","$$$$$").replace("*****","$$$$$").replace("&&&&&","$$$$$");
            //分割入库
            String[] split = textContent.split(splits);
            for (String s : split) {
                if (s.trim().length() > 5) {
                    TenderContent testContent = new TenderContent();
                    testContent.setContent(s);
                    IndexResponse indexResponse = client.index(i -> i
                            .index(indexName)
                            //设置id
                            //.id("1")
                            //传入user对象
                            .document(testContent));
                }
            }
        }
    }

    public void addContentByIndexId(String indexName, String content) throws Exception {

        TenderContent testContent = new TenderContent();
        testContent.setContent(content);
        IndexResponse indexResponse = client.index(i -> i
                .index(indexName)
                //设置id
                //.id("1")
                //传入user对象
                .document(testContent));
    }

    public String queryOneContent(String indexName, String content) throws IOException {
        String searchContent = content.length() > 500 ? content.substring(0, 500) : content;

        String result = "";
        SearchResponse<TenderContent> search = client.search(s -> s
                        .index(indexName)
                        //查询name字段包含hello的document(不使用分词器精确查找)
                        .query(q -> q
                                .match(m -> m
                                        .field("content")
                                        .query(searchContent) // 这里是你要搜索的文本
                                )
                        )
                        //分页查询，从第0页开始查询3个document
                        .from(0)
                        .size(1)
                //按age降序排序
                , TenderContent.class
        );
        for (Hit<TenderContent> hit : search.hits().hits()) {
            result = result + hit.source().getContent();
        }
        return result;
    }


    //查询
    public String queryContent(String indexName, String searchContent, int size) throws IOException {
        String result = "";
        SearchResponse<TenderContent> search = client.search(s -> s
                        .index(indexName)
                        //查询name字段包含hello的document(不使用分词器精确查找)
                        .query(q -> q
                                .match(m -> m
                                        .field("content")
                                        .query(searchContent) // 这里是你要搜索的文本
                                )
                        )
                        //分页查询，从第0页开始查询3个document
                        .from(0)
                        .size(size)
                //按age降序排序
                , TenderContent.class
        );
        for (Hit<TenderContent> hit : search.hits().hits()) {
            result = result + hit.source().getContent() + "\n=========\n";
        }
        return result;
    }

    public String textContent(String filePath) throws IOException {
        FileReader reader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }

}
